package com.songlanyun.modules.disabilityauth.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.streamquery.BaseBatchData;
import com.songlanyun.common.streamquery.QueryStreamHandLer;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.disabilityauth.model.DisabilityAuditDTO;
import com.songlanyun.modules.disabilityauth.model.DisabilityAuthEntityDTO;
import com.songlanyun.modules.freebag.entity.FreeBag;
import com.songlanyun.modules.freebag.service.FreeBagService;
import com.songlanyun.modules.freebaggive.service.FreeBagGiveService;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.function.Consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.disabilityauth.dao.DisabilityAuthDao;
import com.songlanyun.modules.disabilityauth.entity.DisabilityAuthEntity;
import com.songlanyun.modules.disabilityauth.service.DisabilityAuthService;


@Service("disabilityAuthService")
public class DisabilityAuthServiceImpl extends ServiceImpl<DisabilityAuthDao, DisabilityAuthEntity> implements DisabilityAuthService {

    @Autowired
    private FreeBagService freeBagService;

    @Autowired
    private FreeBagGiveService freeBagGiveService;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public DisabilityAuthEntity create(DisabilityAuthEntity entity) {
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public DisabilityAuthEntity modify(DisabilityAuthEntity entity) {
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String realName = MapUtil.getStr(params, "real_name");
        String mobile = MapUtil.getStr(params, "mobile");
        Integer status = MapUtil.getInt(params, "status");
        LambdaQueryWrapper<DisabilityAuthEntity> wrapper = new LambdaQueryWrapper<DisabilityAuthEntity>()
                .like(StringUtils.isNotBlank(realName), DisabilityAuthEntity::getRealName, realName)
                .like(StringUtils.isNotBlank(mobile), DisabilityAuthEntity::getMobile, mobile)
                .eq(ObjectUtils.isNotNull(status) && status > -1, DisabilityAuthEntity::getStatus, status)
                .orderByDesc(DisabilityAuthEntity::getCreateTime);

        IPage<DisabilityAuthEntity> page = this.page(
                new Query<DisabilityAuthEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void apply(DisabilityAuthEntityDTO dto) {
        DisabilityAuthEntity load = loadByUserId(dto.getUserId());
        if (!ObjectUtils.isNull(load)) {
            throw new RRException("不要重复申请");
        }
        ValidatorUtils.validateEntity(dto);
        DisabilityAuthEntity disabilityAuthEntity = new DisabilityAuthEntity();
        BeanUtil.copyPropertiesIgnoreNull(dto, disabilityAuthEntity);
        disabilityAuthEntity.setStatus(MemberConstant.VerifyStatus.VERIFY_WAIT);
        disabilityAuthEntity.setApplyTime(new Date());
        disabilityAuthEntity.setIscccLable(MemberConstant.IscccLable.getByCode(dto.getIscccLable()));
        this.create(disabilityAuthEntity);

    }

    @Override
    public DisabilityAuthEntity loadByUserId(Long userId) {
        DisabilityAuthEntity disabilityAuthEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<DisabilityAuthEntity>()
                .eq(DisabilityAuthEntity::getUserId, userId)
                .last("limit 1"));

        return disabilityAuthEntity;
    }

    @Override
    public void updateApply(DisabilityAuthEntityDTO dto) {
        DisabilityAuthEntity load = loadByUserId(dto.getUserId());
        if (ObjectUtils.isNull(load)) {
            throw new RRException("您还不存在申请");
        }
        if (MemberConstant.VerifyStatus.VERIFY_PASS.equals(load.getStatus())) {
            throw new RRException("审核通过了不能再修改");
        }
        BeanUtil.copyPropertiesIgnoreNull(dto, load);
        load.setStatus(MemberConstant.VerifyStatus.VERIFY_WAIT);
        load.setIscccLable(MemberConstant.IscccLable.getByCode(dto.getIscccLable()));
        load.setApplyTime(new Date());

        this.modify(load);
    }

    @Override
    public void audit(DisabilityAuditDTO dto) {
        DisabilityAuthEntity disabilityAuthEntity = this.loadById(dto.getId(), true);
        disabilityAuthEntity.setStatus(MemberConstant.VerifyStatus.getByCode(dto.getStatus()));
        if (MemberConstant.VerifyStatus.VERIFY_PASS.equals(disabilityAuthEntity.getStatus())) {
            freeBagService.loadById(dto.getBenefitsPackageId(), true);
            disabilityAuthEntity.setBenefitsPackageId(dto.getBenefitsPackageId());
        }
        disabilityAuthEntity.setReason(dto.getReason());
        disabilityAuthEntity.setAuditAdmin(dto.getAuditAdmin());
        this.modify(disabilityAuthEntity);

        if ((MemberConstant.VerifyStatus.VERIFY_PASS.equals(disabilityAuthEntity.getStatus()))) {
            freeBagGiveService.firstGive(disabilityAuthEntity.getUserId());
        }
    }

    @Override
    public DisabilityAuthEntity loadById(Long id, boolean tw) {
        DisabilityAuthEntity obj = this.getById(id);
        if (tw && ObjectUtils.isNull(obj)) {
            throw new RRException("编号为" + id + "申请不存在");
        }
        return obj;
    }

    @Override
    public void batchProcess(Integer batchSize, Consumer<BaseBatchData> consumer) {
        QueryStreamHandLer<DisabilityAuthEntity> exportResultHandler = new QueryStreamHandLer<>(batchSize);
        exportResultHandler.consumer = consumer;
        sqlSessionTemplate.select("com.songlanyun.modules.disabilityauth.dao.DisabilityAuthDao.selectStreamAllAudit", exportResultHandler);
        exportResultHandler.endProcess();
    }

    @Override
    public Integer loadByFreeBagId(Integer freeBagId) {
        return this.lambdaQuery().eq(DisabilityAuthEntity::getBenefitsPackageId, freeBagId).count();
    }

}
